import React, { useMemo } from "react";
import { useAppSelector } from "../../store";
import { Checkbox, Stepper } from "react-vant";
import "./style.scss";
import { useDispatch } from "react-redux";
import {
  addCarItemCount,
  subCarItemCount,
  switchCarItemCheck,
} from "../../store/car/carReduce";
const Index = () => {
  const car = useAppSelector((state) => state.car.car);
  const dispatch = useDispatch();
  const price = useMemo(() => {
    return car.reduce((p, n) => {
      return n.checked ? p + n.price * n.count : p;
    }, 0);
  }, [car]);
  const count = useMemo(() => {
    return car.reduce((p, n) => {
      return n.checked ? p + n.count : p;
    }, 0);
  }, [car]);
  return (
    <div className="car">
      <div>
        {car.map((v, i) => {
          return (
            <div key={i} className="car-item">
              <Checkbox
                checked={v.checked}
                onChange={() => dispatch(switchCarItemCheck(v.id))}
              ></Checkbox>
              <dl>
                <dt>
                  <img src={v.url} alt="" />
                </dt>
                <dd>
                  <h3>{v.title}</h3>
                  <p>
                    颜色： {v.color} - 尺寸：{v.size}
                  </p>
                  <p>单价： {v.price}</p>
                  <Stepper
                    min={1}
                    onPlus={() => dispatch(addCarItemCount(v.id))}
                    onMinus={() => dispatch(subCarItemCount(v.id))}
                    value={v.count}
                  ></Stepper>
                </dd>
              </dl>
            </div>
          );
        })}
      </div>
      <p>
        总价： {price}
        数量： {count}
      </p>
    </div>
  );
};

export default Index;
